package models.campus;

import models.UUIDModel;
import models.admin.AdminUser;
import models.constants.DeletedStatus;
import models.contract.Contract;
import models.system.Company;
import models.weixin.WeixinData;

import javax.persistence.*;
import java.util.List;

/**
 * 园区.
 */
@Entity
@Table(name = "bd_campuses")
public class Campus extends UUIDModel {

    /**
     * 物业编号
     */
    @Column(name = "code")
    public String code;
    /**
     * 绑定的微信公众号
     */
    @JoinColumn(name = "weixin_data_id")
    @ManyToOne
    public WeixinData weixinData;


    /**
     * 小区所属物业公司
     */
    @JoinColumn(name = "company_id")
    @ManyToOne
    public Company company;


    /**
     * 小区名称
     */
    @Column(name = "name", length = 20)
    public String name;

    /**
     * 详细地址
     */
    @Column(name = "address", length = 50)
    public String address;

    /**
     * 客服电话
     */
    @Column(name = "service_phone", length = 15)
    public String servicePhone;

    /**
     * 负责人姓名
     */
    @Column(name = "manager_name", length = 10)
    public String managerName;

    /**
     * 负责人电话
     */
    @Column(name = "manager_phone", length = 15)
    public String managerPhone;

    /**
     * 联系人
     */
    @Column(name = "linkman_name", length = 10)
    public String linkmanName;

    /**
     * 联系人电话
     */
    @Column(name = "linkman_phone", length = 15)
    public String linkmanPhone;

    /**
     * 备注信息
     */
    @Column(name = "remark", length = 100)
    public String remark;


    /**
     *
     * @param id
     * @return
     */
    public static Campus findByIdAndUnDeleted(String id) {
        return Campus.find("id = ?1 and deleted = ?2", id, DeletedStatus.UN_DELETED).first();
    }

    /**
     * 加载所有在用园区
     * @return
     */
    public static List<Campus> loadAllCampus( AdminUser loginUser){
        if(loginUser.organization != null)
            return  Campus.find("deleted = ? and belongCompany.id = ? " , DeletedStatus.UN_DELETED , loginUser.organization.getId()).fetch() ;
        return Campus.find("deleted = ?" , DeletedStatus.UN_DELETED).fetch() ;
    }

    /**
     * 检查该园区下是否有在用的楼宇
     * @param campusId
     * @return
     */
    public static Boolean checkIsUsed(String campusId){
        return Building.count("campus.id = ? and deleted = ? " ,campusId , DeletedStatus.UN_DELETED) > 0 ;
    }

    /**
     * 检查物业是否已经存在
     * @param campusName
     * @return
     */
    public static Boolean checkByName(String campusName){
        return Campus.count(" deleted = 0 and name = ?" , campusName) > 0 ;
    }
    /**
     * 根据物业名称查询
     * @param campusName
     * @return
     */
    public static Campus findByName(String campusName){
        return Campus.find(" deleted = 0 and name = ?" , campusName).first();
    }

}
